package com.library.service.impl;

import com.library.entity.User;
import com.library.security.JwtTokenProvider;
import com.library.service.UserAuthService;
import com.library.service.UserService;
import com.library.util.ResultUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Service
public class UserAuthServiceImpl implements UserAuthService {

    private final Set<String> invalidTokens = new HashSet<>();

    @Resource
    private UserService userService;

    @Resource
    private JwtTokenProvider jwtTokenProvider;

    @Override
    public ResultUtil<Map<String, Object>> login(String username, String password) {
        // 1. 查询用户
        User user = userService.findByUsername(username);

        // 2. 验证失败情况 - 直接创建指定泛型的ResultUtil对象
        if (user == null || !userService.verifyPassword(user, password)) {
            ResultUtil<Map<String, Object>> errorResult = new ResultUtil<>();
            errorResult.setCode(1);
            errorResult.setMessage("用户名或密码错误");
            errorResult.setData(null);
            return errorResult;
        }

        // 3. 验证成功 - 生成Token并返回
        String token = jwtTokenProvider.generateToken(user.getUsername());
        Map<String, Object> resultData = new HashMap<>();
        resultData.put("token", token);
        resultData.put("user", user);

        // 4. 构建成功结果 - 明确指定泛型
        ResultUtil<Map<String, Object>> successResult = new ResultUtil<>();
        successResult.setCode(0);
        successResult.setMessage("登录成功");
        successResult.setData(resultData);
        return successResult;
    }

    @Override
    public void logout(String token) {
        if (token != null && !token.isEmpty()) {
            invalidTokens.add(token);
        }
    }

    @Override
    public boolean validateToken(String token) {
        if (invalidTokens.contains(token)) {
            return false;
        }
        return jwtTokenProvider.validateToken(token);
    }

    @Override
    public String getUsernameFromToken(String token) {
        return jwtTokenProvider.getUsernameFromToken(token);
    }
}
